<!--
 * @Author: 小花
 * @Date: 2022-04-23 14:58:37
 * @LastEditors: 小花
 * @LastEditTime: 2022-05-15 16:10:50
 * @FilePath: /vue3-teap/src/components/AddAdmin.vue
 * @Description:
-->
<template>
  <el-drawer v-model="drawerVisible" direction="btt" size="85%">
    <template #title>
      <h4>新增管理员</h4>
    </template>
    <template #default>
      <div class="form">
        <el-form label-position="right" label-width="100px" :model="formData"
          style="max-width: 460px" :rules="FormRules" ref="ruleFormRef">
          <el-form-item prop="name" label="姓名">
            <el-input clearable v-model="formData.name" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item prop="account" label="账号">
            <el-input clearable v-model="formData.account" placeholder="请输入账号(身份证号)" />
          </el-form-item>
          <el-form-item prop="password" label="初始密码">
            <el-input clearable :model-value="formData.password" disabled readonly />
          </el-form-item>
          <el-form-item prop="phone" label="电话">
            <el-input clearable v-model="formData.phone" placeholder="请输入电话" />
          </el-form-item>
          <el-form-item prop="email" label="邮箱">
            <el-input clearable type="email" v-model="formData.email" placeholder="请输入邮箱地址" />
          </el-form-item>
          <el-form-item prop="roleId" label="角色">
            <el-select v-model="formData.roleId" class="m-2" placeholder="Select">
              <el-option v-for="item in roleList" :key="item.roleId" :label="item.roleName"
                :value="item.roleId" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </template>
    <template #footer>
      <div class="footer">
        <el-button @click="resetForm(ruleFormRef)">取消
        </el-button>
        <el-button type="primary" @click="confirmFormData(ruleFormRef)">新增
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script lang='ts'>
import { ElMessage, ElNotification, FormInstance } from 'element-plus'
import { defineComponent, reactive, toRefs } from 'vue'
import AddAdminData, { FormRules } from '@/model/main/layout/dynamicNav/AdminPage/AddAdmin'
import { addNewAdmin, pullRole } from '@/plugins/request/http'
import { responseEnum, responseUtil } from '@/plugins/request/responseUtil'
import { IAdmin } from '@/model/main/layout/dynamicNav/AdminPage'
import { Md5 } from 'ts-md5/dist/md5'
import _cloneDeep from 'lodash/cloneDeep'
import nProgress from 'nprogress'
import { IRole } from '@/model/main/layout/dynamicNav/PermissionPage/RoleManage'

export default defineComponent({
  name: 'AddAdmin',
  emits: ['execPullAllAdmin'],
  setup (props, { emit }) {
    const coreData = reactive(new AddAdminData())

    /**
     * @description: 后端获取角色信息
     * @return {*}
     */
    const execPullRole = async () => {
      nProgress.start()
      const result = await (await pullRole()).data as responseUtil<IRole[]>
      coreData.roleList = result.data || []
      coreData.roleList.some(item => {
        if (item.roleName.includes('管理员')) {
          coreData.formData.roleId = item.roleId
          return true
        }
        return false
      })
      nProgress.done()
    }
    execPullRole()

    /**
     * @description: 固定初始化管理登录密码
     * @return {*}
     */
    coreData.formData.password = '123456'

    const resetForm = (formEl: FormInstance | undefined) => {
      if (!formEl) return
      formEl.resetFields()
      coreData.drawerVisible = false
    }

    /**
     * @description: 确认并验证表单数据
     * @param undefined
     * @return {*}
     */
    const confirmFormData = async (formEl: FormInstance | undefined) => {
      if (!formEl) return
      await formEl.validate((valid, fields) => {
        if (valid) {
          execAddNewAdmin()
        } else {
          let reason = '\n'
          Object.keys(fields as object).forEach((item, index) => {
            reason += `ErrorReason${index}: '${(fields as any)[item][0].fieldValue}'\n`
          })
          confirm(`添加信息存在错误, 请重新修改.${reason}`)
        }
      })
    }

    /**
     * @description: 执行添加新管理员处理器
     * @return {*}
     */
    const execAddNewAdmin = async () => {
      const encrypt: IAdmin = _cloneDeep(coreData.formData)
      encrypt.account = Md5.hashStr(encrypt.account)
      encrypt.password = Md5.hashStr(encrypt.password)
      const result = await (await addNewAdmin(encrypt)).data as responseUtil
      if (result.code === responseEnum.PARAMS_ERROR || result.code !== responseEnum.OK) {
        ElMessage.error(result.msg)
        return
      }
      resetForm(coreData.ruleFormRef)

      emit('execPullAllAdmin')

      ElNotification.success({
        title: 'Success',
        message: result.msg
      })
    }

    return {
      ...toRefs(coreData),
      FormRules,
      resetForm,
      confirmFormData
    }
  }
})
</script>

<style lang='scss' scoped>
@import '@/assets/scss/el-drawer.scss';
</style>
